import express from "express";
import { Database } from "../model/database";
import { vaild, sign } from "../middleware/jwt";
import crypto from "crypto";
import reptile from "../middleware/reptile";

class Times {
    timeString !:string;
    max !:number;
    stop !:number;
}
let dates:Array<Date> = new Array(4).fill(new Date());
let datesNum:Array<number> = new Array();
for(let i = 0; i < dates.length; i++) {
    dates[i].setDate(22 + i);
    dates[i].setHours(22);
    dates[i].setMinutes(0);
    dates[i].setSeconds(0);
    datesNum.push(dates[i].getTime())
}

const times:Array<Times> = [
    {timeString: "周日晚上20：00", max: 30, stop: datesNum[0]}, /* 0 */
    {timeString: "周日晚上20：00", max: 30, stop: datesNum[1]}, /* 1 */
    {timeString: "周日晚上20：00", max: 30, stop: datesNum[2]}, /* 2 */
    {timeString: "周日晚上20：00", max: 30, stop: datesNum[3]}, /* 3 */
]


export default function(app:express.Application, db:Database){
    app.get("/api/mob/query-applicant-result",(req:any, res:any)=>{
        //验证token
        const token:any= typeof req.header("token") === "string"? req.header("token"):"";
        vaild(token).then((data:any) => {
            return db.queryStuInformByID(data.id);
        }).then((data:any) => {
            let timeStr = data[0].time < 0 ? "" : times[data[0].time].timeString;
            let resMsg = {
                status: 0,
                msg: "OK",
                result: {
                    tel: data[0].tel,
                    group: data[0].group,
                    result: data[0].state,
                    time: timeStr,
                    name: data[0].name,
                    class: data[0].class
                }
            }
            res.send(JSON.stringify(resMsg));
            res.end();
        }).catch((err) => {
            console.log(err);
            let resMsg = {
                status: 3,
                msg: "database err",
                result: {},
            };
            res.send(resMsg);
            res.end();
        });        
    });

    app.get("/api/mob/query-number-of-people",(req:any, res:any)=>{
        const group:any = req.query.group;
        let arr = new Array();

        new Promise((resolve, rej) => {
            (async () => {
                for(let i = 0; i < times.length; i++) {
                    let data = await db.queryNumByTime(i, parseInt(group));
                    let date = new Date();
                    if(data < times[i].max && date.getTime() < times[i].stop) {
                        arr.push({
                            code: i,
                            timeString: times[i].timeString,
                        })
                    }
                    if(i === times.length - 1) {
                        resolve(arr);
                    }
                    
                }
            })()
        }).then((data) => {
            let resMsg = {
                status: 0,
                msg: "OK",
                result: data,
            }
            res.send(resMsg);
            res.end();
        }).catch((err) => {
            console.log(err);
            let resMsg = {
                status: 3,
                msg: "database err",
                result: false
            };
            res.send(resMsg);
            res.end();
        });        
    });


  

    let beforeId:string;
    app.post("/api/mob/login-school",(req:any, res:any)=>{
        console.log("login...");
        let id = req.body.id;
        let password = req.body.password;
        setTimeout(() => {
            beforeId = "";
        }, 1000);
        if(id.length != 8) {
            let resMsg:string = JSON.stringify({
                status: 2,
                msg: "学号不合法",
                result: false
            });
            res.send(resMsg);
            res.end();
        }
        else if(beforeId === id) {
            let resMsg:string = JSON.stringify({
                status: 2,
                msg: "短时间内请勿重复登录",
                result: false
            });
            res.send(resMsg);
            res.end();
        } else{
            beforeId = id;
            try {
            
                let md5 = crypto.createHash("md5"); // 创建 md5
                let md5Sum = md5.update(password); // update 加密
                let result = md5Sum.digest("hex"); // 获取加密后结果
                //查询是否在数据库内    
                db.queryStuPassByID(id).then((data:any) => {
                    if(!data.length) {
                        console.log("爬");
                        reptile(id, password).then((value:any) => {
                            if(!value.tips && value.state === 0) {
                                let resMsg:string = JSON.stringify({
                                    status: 0,
                                    msg: "",
                                    result: true
                                });
                                
                                //保存
                                Promise.all([
                                    db.insertTostuPass({
                                        id: id,
                                        password: result
                                    }),
                                    db.insertTostuInform({
                                        id: id,
                                        state: -1,
                                        group: undefined,
                                        name: value.name,
                                        class: value.class,
                                        qq: undefined,
                                        tel: undefined,
                                        why: undefined,
                                        hobby: undefined,
                                        time: undefined,
                                        firstscore: 0,
                                        secondscore: 0,
                                        thirdscore: 0,
                                        fourthscore: 0
                                    })
                                ]).then(() => {
                                    console.log("保存成功");
                                    sign(id).then((token:any) => {
                                        res.setHeader("token", token);
                                        res.send(resMsg);
                                        res.end();
                                    })
                                    
                                 })
                                
                                
                            } else if(value.state === 0) {
                                let resMsg:string = JSON.stringify({
                                    status: 2,
                                    msg: value.tips.split("\n")[0],
                                    result: false
                                });
                                res.send(resMsg);
                                res.end();
                            } else {
                                let resMsg:string = JSON.stringify({
                                    status: 3,
                                    msg: value.tips,
                                    result: false
                                });
                                res.send(resMsg);
                                res.end();
                            }
                            
                        });
                    } else {
                        //如果在
                        //验证并返回
                        if(result === data[0].password) {
                            db.queryStuInformByID(id).then((data:any) => {
                                let resMsg:string = JSON.stringify({
                                    status: 0,
                                    msg: "OK",
                                    result: true
                                });
                                sign(id).then((token:any) => {
                                    res.setHeader("token", token);
                                    res.send(resMsg);
                                    res.end();
                                });
                            });
                        } else {
                            let resMsg:string = JSON.stringify({
                                status: 2,
                                msg: "学号或密码不正确",
                                result: false
                            });
                            res.send(resMsg);
                            res.end();
                        }
                    }
                });
            } catch(err) {
                console.log(err);
                let resMsg:string = JSON.stringify({
                    status: 3,
                    msg: err,
                    result: false
                });
                res.send(resMsg);
                res.end();
            }
        }
    }); 

    app.get("/api/mob/is-apply",(req:any, res:any)=>{
        //验证token
        const token:any= typeof req.header("token") === "string"? req.header("token"):"";
        vaild(token).then((data:any) => {
            return db.queryStuInformByID(data.id);
        }).then((data:any) => {
            let resMsg = {
                status: 0,
                msg: "OK",
                result: data[0].state > 0 ? true : false
            }
            res.send(resMsg);
            res.end();
        }).catch((err) => {
            console.log(err);
            let resMsg = {
                status: 3,
                msg: err,
                result: false,
            };
            res.send(resMsg);
            res.end();
        });        
    });

    app.post("/api/mob/apply",(req:any, res:any)=>{
        //验证token
        const token:any= typeof req.header("token") === "string"? req.header("token"):"";
        let ePattern = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if(!ePattern.test(req.body.qq)){
            let resMsg = {
                status: 2,
                msg:"邮箱格式问题",
            };
            res.send(resMsg);
            res.end();
        }
        vaild(token).then((data:any) => {
            return db.queryStuInformByID(data.id);
        }).then((data) => {
            if(!data.length || data[0].state > 0) {
                return new Promise((res, rej) => {
                    rej(200);
                });
            } else {
                return db.queryBySQL(`UPDATE stu_infom_table SET 
                \`group\`=${req.body.group},time=${req.body.time},tel='${req.body.tel}',qq='${req.body.qq}',why='${req.body.why}',hobby='${req.body.hobby}',state=100
                WHERE id=${data[0].id}`);
            }    
        }).then((data:any) => {
            let resMsg = {
                status: 0,
                msg:"OK",
                result: true,
            };
            res.send(resMsg);
            res.end();
        }).catch((err) => {
            console.log(err);
            let state:number = 3;
            let result:boolean = false;
            let resMsg = {
                status: state,
                msg: "服务器内部未知错误，请联系后台或到后台控制台查看详情",
                result: result,
            };
            if(err === 200) {
                resMsg.msg = "请勿重复报名";
            }
            res.send(resMsg);
            res.end();
        });
    });

}